package com.jty.module_main.viewmodel

import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.jty.lib_base.base.BaseBean
import com.jty.lib_base.base.BaseViewModel
import com.jty.lib_base.base.MyApplication
import com.jty.lib_base.binding.command.BindingAction
import com.jty.lib_base.binding.command.BindingCommand
import com.jty.lib_base.bus.event.SingleLiveEvent
import com.jty.lib_base.data.DataRepository
import com.jty.lib_base.data.bean.PageBybookNoteBean
import com.jty.lib_base.event.LiveBusCenter
import com.jty.lib_base.extension.ApiSubscriptHelper
import com.jty.lib_base.room.AppDatabase
import com.jty.lib_base.room.bean.BookNote
import com.jty.lib_base.utils.ComUtils
import com.jty.lib_base.utils.RxThreadHelper
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import okhttp3.RequestBody
import java.util.concurrent.TimeUnit


/**
 * author: zhouyh
 * created on: 2021/9/18 5:35 下午
 * description:主页viewmodel
 */
class NoteViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var mPageBean = MutableLiveData<PageBybookNoteBean>()
    var mIsPenConnect = ObservableBoolean(false)
    var mPenMac = ObservableField<String>("MAC: ")
    var mVarbatteryPercent = ObservableInt(0)
    var mMemoryPercent = ObservableInt(0)
    var mMemoryByteNum = ObservableInt(0)
    var mIsNoData = ObservableBoolean(false)

    val uc = UIChangeEvent()

    /**
     * UI刷新事件 用于观察者
     */
    class UIChangeEvent{
        val clickPenConnect: SingleLiveEvent<Void> = SingleLiveEvent()
        val clickPenDisConnect: SingleLiveEvent<Void> = SingleLiveEvent()
        val finishSmart: SingleLiveEvent<Int> = SingleLiveEvent()
    }


    override fun onCreate() {
        super.onCreate()
        tvTitle.set("笔记")
        btnBackVisibility.set(false)
    }

    //viewModel.pageBybookNote(1)使用这个替换了
    /*override fun onResume() {
        super.onResume()
        var isChange = false
        mPageBean.value?.records?.let {
            for(item in it) {
                val b = AppDatabase.getInstance().bookNoteDao().queryById(item.id.toLong())
                if(b?.lastPageNum != item.lastPage) {
                    item.lastPage = b?.lastPageNum!!
                    isChange = true
                }
            }
        }

        if(isChange) {
            mPageBean.postValue(mPageBean.value)
        }

    }*/

    override fun onResume() {
        super.onResume()
        Observable.timer(300, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : Observer<Long> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(aLong: Long) {
                    LiveBusCenter.postToPenNoSubmitEvent() //为了程序奔溃导致笔记没有提交到后台，笔记预览做了每1分钟保存到本地
                    LiveBusCenter.postToVersionUpdateEvent(false)
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}
            })

    }

    val onClickConnect: BindingCommand<Void> = BindingCommand(BindingAction {
        if(!mIsPenConnect.get())  uc.clickPenConnect.call()
    })

    val onClickDisconnect: BindingCommand<Void> = BindingCommand(BindingAction {
        if(mIsPenConnect.get())  uc.clickPenDisConnect.call()
    })



    fun setmIsPenConnect(isCon: Boolean) {
        mIsPenConnect.set(isCon)
    }

    fun setmPenMac(mac:String) {
        mPenMac.set("MAC: ${mac}")
    }

    fun setPenInfo(batteryPercent: Int, memoryPercent: Int, memoryByteNum: Int) {
        mVarbatteryPercent.set(batteryPercent)
        mMemoryPercent.set(memoryPercent)
        mMemoryByteNum.set(memoryByteNum)
    }

    //viewModel.pageBybookNote(1) 使用这个替换了
    /*fun refreshLastWrite(g: GridPicture) {
        var b = false
        mPageBean.value?.records?.let{
            for(item in it) {
                if(item.id == g.bookNoteId?.toInt()) {
                    item.lastPage = g.pageNumber
                    b = true
                }
            }
        }
        if(b) {
            mPageBean.postValue(mPageBean.value)
        }

    }*/

    fun pageBybookNote(cur: Int) {
        val json = ComUtils.getHashmapByStr(
            arrayOf("pageNo", "pageSize"),
            arrayOf(cur.toString(), "10")
        )
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))

        model.apply {
            this.pageBybookNote(requestBody)
                .compose(RxThreadHelper.rxSchedulerHelper(this@NoteViewModel))
                .doOnSubscribe { }
                .subscribe(object : ApiSubscriptHelper<BaseBean<PageBybookNoteBean>>() {
                    override fun onResult(t: BaseBean<PageBybookNoteBean>) {
                        uc.finishSmart.postValue(cur)
                        if (t.code == 0) {
                            //Logger.e("aaa---${t.data?.records?.get(0)?.coverUrl}")
                            //Logger.e("aaa---${t.data?.records?.get(0)?.name}")
                            t.data?.let {
                                for(item in it.records) {
                                    val bookNote =AppDatabase.getInstance().bookNoteDao().queryById(item.id.toLong())
                                    if(bookNote == null) {
                                        AppDatabase.getInstance().bookNoteDao().insertAll(
                                            BookNote(item.id.toLong(),
                                                item.name,
                                                item.pageNum,
                                                item.lastPage,
                                                item.allowWrite,
                                                item.coverUrl)
                                        )
                                    } else if(item.name != bookNote.name
                                        || item.coverUrl != bookNote.coverUrl
                                        || item.pageNum != bookNote.pageNum
                                        || item.allowWrite != bookNote.allowWrite
                                        || item.lastPage != bookNote.lastPageNum) {
                                        bookNote.name = item.name
                                        bookNote.coverUrl = item.coverUrl
                                        bookNote.pageNum = item.pageNum
                                        bookNote.lastPageNum = item.lastPage
                                        bookNote.allowWrite = item.allowWrite
                                        AppDatabase.getInstance().bookNoteDao().updateBookNotes(bookNote)
                                    }
                                }
                                if(cur == 1) {
                                    if(it.records.isNullOrEmpty()) {
                                        mIsNoData.set(true)
                                    } else {
                                        mIsNoData.set(false)
                                    }
                                    mPageBean.postValue(it)
                                } else {
                                    it.records.addAll(0, mPageBean.value!!.records)
                                    mPageBean.postValue(it)
                                }
                            }
                        }
                    }

                    override fun onFailed(msg: String?) {
                        uc.finishSmart.postValue(cur)
                        showNormalToast(msg)
                    }
                })
        }
    }
}